# coding: utf-8
def index():
    if (request.env.request_method == 'GET'):
        print 'get'
        return WeixinInterface().GET()
    else:
        print 'post'
        return WeixinInterface().POST()

class WeixinInterface:
    def __init__(self):
        self.reply_text = """
        <xml>
            <ToUserName><![CDATA[{{=toUser}}]]></ToUserName>
            <FromUserName><![CDATA[{{=fromUser}}]]></FromUserName>
            <CreateTime>{{=createTime}}</CreateTime>
            <MsgType><![CDATA[text]]></MsgType>
            <Content>{{=content}}</Content>
        </xml>
        """
        self.reply_news = """
        <xml>
            <ToUserName><![CDATA[{{=toUser}}]]></ToUserName>
            <FromUserName><![CDATA[{{=fromUser}}]]></FromUserName>
            <CreateTime>{{=createTime}}</CreateTime>
            <MsgType><![CDATA[news]]></MsgType>
            <ArticleCount>{{=len(news)}}</ArticleCount>
            <Articles>
            {{for item in news:}}
                <item>
                    <Title><![CDATA[{{=item['title']}}]]></Title>
                    <Description><![CDATA[{{=item['description']}}]]></Description>
                    <PicUrl><![CDATA[{{=item['picurl']}}]]></PicUrl>
                    <Url><![CDATA[{{=item['url']}}]]></Url>
                </item>
            {{pass}}
            </Articles>
        </xml>
        """
        self.reply_video = """
        <xml>
            <ToUserName><![CDATA[{{=toUser}}]]></ToUserName>
            <FromUserName><![CDATA[{{=fromUser}}]]></FromUserName>
            <CreateTime>{{=createTime}}</CreateTime>
            <MsgType><![CDATA[video]]></MsgType>
            <Video>
                <MediaId><![CDATA[{{=media_id}}]]></MediaId>
                <Title><![CDATA[{{=title}}]]></Title>
                <Description><![CDATA[{{=description}}]]></Description>
            </Video>
        </xml>
         """
        self.reply_voice = """
        <xml>
            <ToUserName><![CDATA[{{=toUser}}]]></ToUserName>
            <FromUserName><![CDATA[{{=fromUser}}]]></FromUserName>
            <CreateTime>$createTime</CreateTime>
            <MsgType><![CDATA[voice]]></MsgType>
            <Voice>
                <MediaId><![CDATA[{{=media_id}}]]></MediaId>
            </Voice>
        </xml>
        """
        self.reply_image = """
        <xml>
            <ToUserName><![CDATA[{{=toUser}}]]></ToUserName>
            <FromUserName><![CDATA[{{=fromUser}}]]></FromUserName>
            <CreateTime>{{=createTime}}</CreateTime>
            <MsgType><![CDATA[image]]></MsgType>
            <Image>
                <MediaId><![CDATA[{{=media_id}}]]></MediaId>
            </Image>
        </xml>
         """
        self.reply_music = """
        <xml>
            <ToUserName><![CDATA[{{=toUser}}]]></ToUserName>
            <FromUserName><![CDATA[{{=fromUser}}]]></FromUserName>
            <CreateTime>{{=createTime}}</CreateTime>
            <MsgType><![CDATA[music]]></MsgType>
            <Music>
                <Title><![CDATA[{{=musicTitle}}]]></Title>
                <Description><![CDATA[{{=musicDes}}]]></Description>
                <MusicUrl><![CDATA[{{=musicURL}}]]></MusicUrl>
                <HQMusicUrl><![CDATA[{{=hqmusicURL}}]]></HQMusicUrl>
            </Music>
            <FuncFlag>0</FuncFlag>
        </xml>
         """
        print 'WeixinInterface reset'

    def GET(self):
        data = request.vars
        signature = data.signature
        timestamp = data.timestamp
        nonce = data.nonce
        echostr = data.echostr
        # 自己的token
        token = "pycube"
        encodingAESKey = "4ZXiiPH7Lv0lSv9MvmRPO0HZZUj7R0kwOLtjYMFfikU"
        list = [token, timestamp, nonce]
        list.sort()
        import hashlib
        sha1 = hashlib.sha1()
        map(sha1.update, list)
        hashcode = sha1.hexdigest()
        # 如果是来自微信的请求，则回复echostr
        if hashcode == signature:
            return echostr
        return None
    def POST(self):
        import time
        import xml.etree.ElementTree as ET
        import gluon.template as TE
        # 获取post来的数据
        xml = ET.parse(request.body)  # 进行XML解析
        # 提取信息
        msgtype = xml.findtext("MsgType")
        fromUser = xml.findtext("FromUserName")
        toUser = xml.findtext("ToUserName")
        if msgtype == "event":
            mscontent = xml.findtext("Event")
            if mscontent == "subscribe":
                replyText = u'欢迎关注魔方小助手\ud83d\udc7b！\n输入help获取操作指南'
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=replyText))
            if mscontent == "unsubscribe":
                replyText = u'欢迎您以后再来！！'
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=replyText))
            if mscontent == "CLICK":
                eventkey = xml.findtext("EventKey")
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=eventkey))
        # 图片识别
        if msgtype == 'image':
            url = xml.findtext("PicUrl")
            replyText = Face().getface(url)
            return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=replyText))
        # 语音识别
        if msgtype == 'voice':
            content = xml.findtext("Recognition")
            print content
            if content == '':
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=u'你什么也没说呀，还能不能玩耍了'))
        if msgtype == 'text' or msgtype == 'voice' or msgtype == 'event':
            if msgtype == 'text':
                content = xml.findtext("Content").strip()
            if msgtype == 'voice':
                content = xml.findtext("Recognition")
            if msgtype == 'event':
                mscontent = xml.findtext("Event")
                if mscontent == "CLICK":
                    content = xml.findtext("EventKey")
            if content == 'help':
                list = [u'您好，我是魔方小助手\ud83d\udc7b\n请回复数字选择服务：']
                list.append(u'\n')
                list.append(u'\n1\t天气预报')
                list.append(u'\n2\t历史上的今天')
                list.append(u'\n3\t歌曲点播')
                list.append(u'\n4\t人脸识别')
                list.append(u'\n5\t聊天唠嗑')
                list.append(u'\n6\t翻译助手')
                list.append(u'\n7\t幽默笑话')
                list.append(u'\n8\t挑战2048')
                # list.append(u'\n9\t模拟考勤')
                list.append(u'\n0\t反馈意见\n\n')
                list.append(u'点击查看<a href=djsoft.sinaapp.com>个人主页</a>\n可以语音识别⊙０⊙')
                replyText = ''.join(list)
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=replyText))
            if content == '1':
                replyText = Weather().getUsage()
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=replyText))
            if content == '2':
                content = 'ls'
            if content == '3':
                replyText = Baidumusic().getUsage()
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=replyText))
            if content == '4':
                replyText = ''
                replyText=Face().getUsage()
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=replyText))
            if content == '5':
                replyText = ''
                replyText=Ask().getUsage()
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=replyText))
            if content == '6':
                replyText=Trans().getUsage()
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=replyText))
            if content == '7':
                content = 'joke'
            if content == '8':
                content = '2048'
            if content == '9':
                list = [u'\ud83d\ude84模拟考勤使用指南\n\n']
                list.append(u'模拟考勤系统，真的好像\n')
                list.append(u'使用示例：\n')
                list.append(u'打没打:\t进行考勤确认\n')
                list.append(u'查看:\t进行确认查看\n')
                list.append(u'绑定:\t绑定用户信息\n\n')
                # list.append(u'回复打一下，进行考勤\n\n')
                list.append(u'回复“help”显示主菜单')
                replyText = ''.join(list)
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=replyText))
            if content == '0':
                list = [u'\ud83d\udcbb反馈意见使用指南\n\n']
                list.append(u'fk+反馈信息\n\n')
                list.append(u'使用示例：\n')
                list.append(u'fk添加个微社区呗\n')
                list.append(u'fk能搜索图片么？\n\n')
                list.append(u'点击查看<a href=djsoft.sinaapp.com>反馈列表</a>\n')
                list.append(u'回复“help”显示主菜单')
                replyText = ''.join(list)
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=replyText))
                # 反馈用户信息***************************************
            if content.startswith('fk'):
                fktime = time.strftime('%Y-%m-%d %H:%M', time.localtime())
                # model.addfk(fromUser,fktime,content[2:].encode('utf-8'))
                return self.render.reply_text(fromUser, toUser, int(time.time()), u'感谢您的反馈')
            if content == u'查看':
                try:
                    # user=model.query_user_pw(fromUser)[0]
                    # if user.username<>'':
                    if 'user' <> '':
                        list = [{'title': u'魔方小助手',
                                 'description': '',
                                 'picurl': '',
                                 'url': 'djsoft.sinaapp.com/kq?openid=' + fromUser}]
                        list.append({'title': u'点击查看结果信息',
                                     'description': '',
                                     'picurl': 'http://djsoft.sinaapp.com/static/images/kq.png',
                                     'url': 'djsoft.sinaapp.com/kq?openid=' + fromUser})
                except:
                    list = [{'title': u'魔方小助手',
                             'description': '',
                             'picurl': '',
                             'url': 'djsoft.sinaapp.com/reg?name=' + fromUser}]
                    list.append({'title': u'需要先绑定用户信息',
                                 'description': '',
                                 'picurl': 'http://djsoft.sinaapp.com/static/images/kq.png',
                                 'url': 'djsoft.sinaapp.com/reg?name=' + fromUser})
                    pass
                return self.render.reply_news(fromUser, toUser, int(time.time()), list)
            if content == u'打没打' or content == u'打一下':
                try:
                    # user=model.query_user_pw(fromUser)[0]
                    # if user.username<>''
                    if 'user' <> '':
                        # 发邮件处理
                        cardtpye = '99'
                        if content == u'打一下':
                            cardtpye = '1'
                            # sub='card:'+user.username+':'+user.password+':'+cardtpye+':'+fromUser
                            # flag = mailwx.send_mail(sub,'hello world')
                            # print flag
                            # if flag:
                            list = [{'title': u'魔方小助手',
                                     'description': '',
                                     'picurl': '',
                                     'url': 'djsoft.sinaapp.com/kq?openid=' + fromUser}]
                            list.append({'title': u'处理成功!\r\n一分钟后点击本消息进行结果确认或者回复“查看”点击链接进行查看\r\n修改用户信息回复“绑定”',
                                         'description': '',
                                         'picurl': 'http://djsoft.sinaapp.com/static/images/kq.png',
                                         'url': 'djsoft.sinaapp.com/kq?openid=' + fromUser})
                            return self.render.reply_news(fromUser, toUser, int(time.time()), list)
                        return self.render.reply_text(fromUser, toUser, int(time.time()), u'处理请求失败稍后再试!')
                except Exception, e:
                    print str(e)
                    pass
                list = [{'title': u'魔方小助手',
                         'description': '',
                         'picurl': '',
                         'url': 'djsoft.sinaapp.com/reg?name=' + fromUser}]
                list.append({'title': u'需要先绑定用户信息',
                             'description': '',
                             'picurl': 'http://djsoft.sinaapp.com/static/images/kq.png',
                             'url': 'djsoft.sinaapp.com/reg?name=' + fromUser})
                return self.render.reply_news(fromUser, toUser, int(time.time()), list)
            if content == u'绑定':
                list = [{'title': u'魔方小助手',
                         'description': '',
                         'picurl': '',
                         'url': 'djsoft.sinaapp.com/reg?name=' + fromUser}]
                list.append({'title': u'绑定用户信息',
                             'description': '',
                             'picurl': 'http://djsoft.sinaapp.com/static/images/kq.png',
                             'url': 'djsoft.sinaapp.com/reg?name=' + fromUser})
                return self.render.reply_news(fromUser, toUser, int(time.time()), list)

            if content == 'joke':
                replyText = Joke().getjoke()
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=replyText))
            if content == 'ls':
                replyText = Historytoday().gethistory()
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=replyText))
            if content.startswith(u'歌曲'):
                # str=u'歌曲 今天 @ 刘德华'
                keyWord = content[2:].replace(' ', '')
                slist = keyWord.split('@')
                author1 = u''
                if len(slist) > 1:
                    author1 = slist[1]
                listmusic=Baidumusic().searchMusic(slist[0],author1)
                if len(listmusic) > 0:
                    return TE.render(content=self.reply_music,
                                     context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()),
                                                  musicTitle=listmusic[2],musicDes=listmusic[3],musicURL=listmusic[0],hqmusicURL=listmusic[1]))
                else:
                    replyText = u'对不起，没有找到你想听的歌曲<' + slist[0] + '>.'
                    return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=replyText))
            if content.startswith(u'天气') or content.endswith(u'天气'):
                city = content.replace(u'天气', '')
                city = city.replace(u' ', '')
                weather_info = Weather().getweather(city)
                if len(weather_info) < 2:
                    return self.render.reply_text(fromUser, toUser, int(time.time()), weather_info[0])
                return self.render.reply_news(fromUser, toUser, int(time.time()), weather_info)

            if content == '2048':
                weather_info = [{'title': '挑战2048', 'description': '快来挑战你的智商',
                                 'picurl': 'http://djsoft.sinaapp.com/static/2048/2048.jpg',
                                 'url': 'http://djsoft.sinaapp.com/game2048'}]
                return TE.render(content=self.reply_news,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), news=weather_info))
            if content.startswith(u'翻译') and len(content) != 2:
                keyWord = content[2:]
                keyWord = keyWord.encode('utf-8')
                Nword = Trans().youdao(keyWord)
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=Nword))
            else:
                list = Ask().getAsk(ask=content,openid=fromUser)
                if len(list) > 1:
                    return TE.render(content=self.reply_news,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), news=list))
                return TE.render(content=self.reply_text,context=dict(fromUser=toUser, toUser=fromUser, createTime=int(time.time()), content=''.join(list)))

class Ask:

    def getUsage(self):
        list = [u'\ud83d\ude37聊天唠嗑使用指南\n\n']
        list.append(u'闲暇无聊，来找魔方小助手唠嗑吧，小助手很能聊的，有问必答！例如：\n')
        list.append(u'\ud83d\udc49 讲个笑话\n')
        list.append(u'\ud83d\udc49 沈阳有什么好玩的\n')
        list.append(u'\ud83d\udc49 沈阳的区号\n')
        list.append(u'\ud83d\udc49 红烧肉怎么做\n')
        list.append(u'\ud83d\udc49 明天沈阳到北京的火车\n')
        list.append(u'\ud83d\udc49 顺丰快递\n')
        list.append(u'\ud83d\udc49 沈阳今天的天气怎么样\n')
        list.append(u'\ud83d\udc49 挖掘机技术哪家强？\n\n')
        list.append(u'回复“help”显示主菜单')
        return ''.join(list)

    def getAsk(self,ask, openid):
        import urllib2, urllib, json
        list = []
        askUrl = 'http://www.tuling123.com/openapi/api?key=11920e84260a8984e3db63a5ea58544a&userid={openid}&info={keyword}'
        url = askUrl.replace("{keyword}", urllib.quote(ask.encode('utf-8')))
        url = url.replace("{openid}", openid)
        html = urllib2.urlopen(url).read()
        # print html
        weatherJSON = json.JSONDecoder().decode(html)
        # print weatherJSON
        code = weatherJSON['code']
        if code == 100000:
            list.append(weatherJSON['text'])
            # print '文本类数据'
            # print weatherJSON['text']
        if code == 305000:
            # print '列车'
            test = ''
            for i in range(len(weatherJSON['list'])):
                test = test + weatherJSON['list'][i]['trainnum'] + '\t ' + weatherJSON['list'][i]['start'] + '-' + \
                       weatherJSON['list'][i]['terminal'] + '\t' + weatherJSON['list'][i]['starttime'] + '-' + \
                       weatherJSON['list'][i]['endtime'] + '\n'
                # print tests['trainnum']+'\t '+tests['start']+'-'+tests['terminal']+'\t'+tests['starttime']+'-'+tests['endtime']+'\n'
            list.append(test)
        if code == 306000:
            # print '航班'
            list.append(u'亲，太为难我了')
        if code == 200000:
            # print '网址类数据' <a href="http://blog.csdn.net/lyq8479">柳峰的博客</a>
            list.append(weatherJSON['text'] + '\n<a href="' + weatherJSON['url'] + '">点击查看</a>')
        if code == 302000:
            # print '新闻'
            list.append({'title': weatherJSON['text'], 'description': '', 'picurl': '', 'url': ''})
            for i in range(len(weatherJSON['list'])):
                list.append({'title': weatherJSON['list'][i]['article'] + '\n' + weatherJSON['list'][i]['source'],
                             'description': '', 'picurl': weatherJSON['list'][i]['icon'],
                             'url': weatherJSON['list'][i]['detailurl']})
        if code == 308000:
            # print '菜谱、视频、小说'
            list.append({'title': weatherJSON['text'], 'description': '', 'picurl': '', 'url': ''})
            for i in range(len(weatherJSON['list'])):
                list.append(
                    {'title': weatherJSON['list'][i]['name'] + '\n' + weatherJSON['list'][i]['info'], 'description': '',
                     'picurl': weatherJSON['list'][i]['icon'], 'url': weatherJSON['list'][i]['detailurl']})
                if i == 4:
                    break
                    # print list
        return list

class Face:
    def getface(self,picurl):
        faceUrl = 'http://apicn.faceplusplus.com/v2/detection/detect?url={local}&api_secret={API_SECRET}&api_key={API_KEY}'
        import urllib2, urllib
        import json
        list = []
        url = faceUrl.replace("{local}", urllib.quote(picurl.encode('utf-8')))
        url = url.replace("{API_KEY}", "4ba03a04a743feeb13fa0bd64ec81259")
        url = url.replace("{API_SECRET}", "Nk13ZB2u0JxOd0HCF8yu9wBfWZm8AANi")
        html = urllib2.urlopen(url).read()
        weatherJSON = json.JSONDecoder().decode(html)
        faces = weatherJSON['face']
        facelist = []
        for face in faces:
            attribute = face["attribute"]
            position = face["position"]
            facelist.append({'age': attribute["age"]["value"], 'gender': self.genderConvert(gender=attribute["gender"]["value"]),
                             'race': self.raceConvert(race=attribute["race"]["value"]), 'centerx': position["center"]["x"],
                             'centery': position["center"]["y"]})
        facelist.sort(key=lambda obj: obj.get('centerx'), reverse=False)
        if len(facelist) >= 1 and len(facelist) <= 10:
            if len(facelist) == 1:
                list.append(u'共检测到' + '%d' % len(facelist) + u'张人脸\n')
            else:
                list.append(u'共检测到' + '%d' % len(facelist) + u'张人脸，按脸部中心位置从左至右依次为：\n')
            for face in facelist:
                list.append(face['race'] + u'人种,')
                list.append(face['gender'] + ',' + '%d' % face['age'] + u'岁左右\n')
            print ''.join(list)
        if len(facelist) > 10:
            list.append(u'共检测到' + '%d' % len(facelist) + u'张人脸\n')
        if len(facelist) == 0:
            list.append(u'未识别到人脸，请换一张清晰的照片再试!')
        return ''.join(list)

    #  性别转换（英文->中文）
    def genderConvert(self,gender):
        result = u'男性';
        if "Male" == gender:
            result = u'男性'
        elif "Female" == gender:
            result = u'女性'
        return result;

    # 人种转换（英文->中文）
    def raceConvert(self,race):
        result = u'黄色'
        if "Asian" == race:
            result = u'黄色'
        elif "White" == race:
            result = u'白色'
        elif "Black" == race:
            result = u'黑色'
        return result

    def getUsage(self):
        list = [u'\ud83d\udcf7人脸检测使用指南\n\n']
        list.append(u'发送一张清晰的照片，就能帮你分析出年龄、性别等信息\n')
        list.append(u'快来试试你是不是长得太着急\n\n')
        list.append(u'回复“help”显示主菜单')
        return ''.join(list)

class Weather:
    def __init__(self):
        self.weatherUrl = 'http://api.map.baidu.com/telematics/v3/weather?location={local}&output=json&ak=SyNk24ez0AexRQNDDYm5qjz5'
    def getweather(self,cityName):
        import urllib2, urllib
        import json, time
        list = []
        url = self.weatherUrl.replace("{local}", urllib.quote(cityName.encode('utf-8')))
        html = urllib2.urlopen(url).read()
        weatherJSON = json.JSONDecoder().decode(html)
        status = weatherJSON['status']
        if status == 'success':
            date = weatherJSON['date']
            results = weatherJSON['results'][0]
            dtitle = results.get('currentCity') + u'天气预报'
            list.append({'title': dtitle, 'description': '', 'picurl': '',
                         'url': 'http://djsoft.sinaapp.com/weather?cityName=' + cityName})
            bw = int(time.strftime('%H', time.localtime()))
            weather_data = results.get('weather_data')
            for i in range(len(weather_data)):
                title = weather_data[i].get('date') + '\n' + weather_data[i].get('weather') + '  ' + weather_data[i].get(
                    'wind') + '  ' + weather_data[i].get('temperature')
                if bw > 18 and bw < 6:
                    list.append({'title': title, 'description': '', 'picurl': weather_data[i].get('nightPictureUrl'),
                                 'url': 'http://djsoft.sinaapp.com/weather?cityName=' + cityName})
                else:
                    list.append({'title': title, 'description': '', 'picurl': weather_data[i].get('dayPictureUrl'),
                                 'url': 'http://djsoft.sinaapp.com/weather?cityName=' + cityName})
        else:
            list.append(u'亲，木有找到该城市的天气信息，请检查城市名称是否拼写正确！')
        return list


    def getweatherhtml(self,cityname):
        import urllib2, urllib
        import json, time
        url = self.weatherUrl.replace("{local}", urllib.quote(cityname.encode('utf-8')))
        html = urllib2.urlopen(url).read()
        weatherJSON = json.JSONDecoder().decode(html)
        status = weatherJSON['status']
        htmltext = [];
        if status == 'success':
            date = weatherJSON['date']
            results = weatherJSON['results'][0]
            dtitle = results.get('currentCity') + u'天气预报'
            htmltext.append('<table style="color: #666;" width="100%">')
            htmltext.append(u'<caption><strong><span style="font-family: 宋体; color: #1f497d">')
            htmltext.append(dtitle)
            htmltext.append('</span></strong></caption>')
            bw = int(time.strftime('%H', time.localtime()))
            weather_data = results.get('weather_data')
            for i in range(len(weather_data)):
                title = weather_data[i].get('date') + '\n' + weather_data[i].get('weather') + '  ' + weather_data[i].get(
                    'wind') + '  ' + weather_data[i].get('temperature')
                if i % 2 == 0:
                    htmltext.append('<tr>')
                else:
                    htmltext.append('<tr style="background-color: #F6F6F6">')
                if bw > 18 and bw < 6:
                    htmltext.append(
                        '<td><img src="' + weather_data[i].get('nightPictureUrl') + '" width="55" height="55" alt="' +
                        weather_data[i].get('weather') + '"></td>')
                else:
                    htmltext.append(
                        '<td><img src="' + weather_data[i].get('dayPictureUrl') + '" width="55" height="55" alt="' +
                        weather_data[i].get('weather') + '"></td>')
                htmltext.append('<td>' + title + '</td>')
                htmltext.append('</tr>')

            htmltext.append(u'<tr><td colspan="2"><font color="red">PM2.5指数：</font>')
            pm25 = int(results.get('pm25'))
            if pm25 > 0 and pm25 <= 50:
                htmltext.append(
                    u'<img src="http://api.map.baidu.com/lbsapi/cloud/cms/carapi/img/pm25green.png" style="max-width:13px; max-height:13px;"> ' + '%d' % pm25 + u' 一级，优')
            if pm25 > 51 and pm25 <= 100:
                htmltext.append(
                    u'<img src="http://api.map.baidu.com/lbsapi/cloud/cms/carapi/img/pm25yellow.png" style="max-width:13px; max-height:13px;"> ' + '%d' % pm25 + u' 二级，良')
            if pm25 > 101 and pm25 <= 150:
                htmltext.append(
                    u'<img src="http://api.map.baidu.com/lbsapi/cloud/cms/carapi/img/pm25orange.png" style="max-width:13px; max-height:13px;"> ' + '%d' % pm25 + u' 三级，轻度污染')
            if pm25 > 151 and pm25 <= 200:
                htmltext.append(
                    u'<img src="http://api.map.baidu.com/lbsapi/cloud/cms/carapi/img/pm25red.png" style="max-width:13px; max-height:13px;"> ' + '%d' % pm25 + u' 四级，中度污染')
            if pm25 > 201 and pm25 <= 300:
                htmltext.append(
                    u'<img src="http://api.map.baidu.com/lbsapi/cloud/cms/carapi/img/pm25purple.png" style="max-width:13px; max-height:13px;"> ' + '%d' % pm25 + u' 五级，重度污染')
            if pm25 > 301:
                htmltext.append(
                    u'<img src="http://api.map.baidu.com/lbsapi/cloud/cms/carapi/img/pm25balck.png" style="max-width:13px; max-height:13px;"> ' + '%d' % pm25 + u' 六级，严重污染')
            htmltext.append('</td></tr>')

            index = results.get('index')
            for i in range(len(index)):
                if i % 2 == 0:
                    htmltext.append('<tr>')
                else:
                    htmltext.append('<tr style="background-color: #F6F6F6">')
                htmltext.append('<td colspan="2"><font color="red">' + index[i].get('tipt') + ':</font>' + index[i].get(
                    'des') + '</td>')
                htmltext.append('</tr>')
            htmltext.append('</table>')
        return ''.join(htmltext)

    def getUsage(self):
        list = [u'\u2600天气预报使用指南\n\n']
        list.append(u'回复 天气+城市名称：\n')
        list.append(u'例如：沈阳天气\n')
        list.append(u'或者：天气沈阳\n\n')
        list.append(u'回复“help”显示主菜单')
        return ''.join(list)

class Baidumusic:
    def searchMusic(musicTitle,musicAuthor):
        listmusic=[]
        import urllib2, urllib
        from xml.dom import minidom
        url = 'http://box.zhangmen.baidu.com/x?op=12&count=1&title={TITLE}$${AUTHOR}$$$$'
        url = url.replace("{TITLE}", urllib.quote(musicTitle.encode('utf-8')))
        url = url.replace("{AUTHOR}", urllib.quote(musicAuthor.encode('utf-8')))
        html = urllib2.urlopen(url).read()
        html = html.decode('gb2312').encode('utf-8')
        html = html.replace('gb2312', 'utf-8')
        #print html
        dom = minidom.parseString(html)
        #得到xml根元素
        root = dom.documentElement
        #count表示搜索到的歌曲数
        count = root.getElementsByTagName('count')[0].firstChild.data
        #当搜索到的歌曲数大于0时
        if count!='0':
            #普通品质
            urlList=root.getElementsByTagName('url')
            # 高品质
            durlList=root.getElementsByTagName('durl')
            #普通品质的encode、decode
            urlEncode=urlList[0].getElementsByTagName('encode')[0].firstChild.data
            urlDecode=urlList[0].getElementsByTagName('decode')[0].firstChild.data
            #普通品质音乐的URL
            url = urlEncode[0:urlEncode.rfind('/')+1] + urlDecode
            if (-1!= urlDecode.rfind("&")):
                url = urlEncode[0:urlEncode.rfind("/") + 1] + urlDecode[0:urlDecode.rfind("&")];
            print url
            #默认情况下，高音质音乐的URL 等于 普通品质音乐的URL
            durl = url
            #判断高品质节点是否存在
            if len(durlList)>0:
                #高品质的encode、decode
                durlEncode=durlList[0].getElementsByTagName('encode')[0].firstChild.data
                durlDecode=durlList[0].getElementsByTagName('decode')[0].firstChild.data
                #高品质音乐的URL
                durl = durlEncode[0:durlEncode.rfind('/')+1] + durlDecode
                if (-1!= durlDecode.rfind("&")):
                    durl = durlEncode[0:durlEncode.rfind("/") + 1] + durlDecode[0:durlDecode.rfind("&")];
                print durl
                listmusic.append(url)
                listmusic.append(durl)
                listmusic.append(musicTitle)
                if musicAuthor!=u'':
                    #如果作者不为""，将描述设置为作者
                     listmusic.append(musicAuthor+u'\n来自魔方小助手')
                else:
                     listmusic.append(u'来自魔方小助手')
        return listmusic

    def getUsage(self):
        list=[u'\ud83c\udfb5歌曲点播操作指南\n\n']
        list.append(u'回复：歌曲+歌名\n')
        list.append(u'例如：歌曲存在\n')
        list.append(u'或者：歌曲存在@汪峰\n\n')
        list.append(u'回复“help”显示主菜单')
        return ''.join(list)

class Trans:
    def youdao(self,word):
        import urllib2
        import json
        qword = urllib2.quote(word)
        baseurl = r'http://fanyi.youdao.com/openapi.do?keyfrom=kaiyao-robot&key=2016811247&type=data&doctype=json&version=1.1&q='
        url = baseurl + qword
        resp = urllib2.urlopen(url)
        fanyi = json.loads(resp.read())
        if fanyi['errorCode'] == 0:
            if 'basic' in fanyi.keys():
                trans = u'%s:\n%s\n%s\n网络释义：\n%s' % (
                fanyi['query'], ''.join(fanyi['translation']), ''.join(fanyi['basic']['explains']),
                ''.join(fanyi['web'][0]['value']))
                return trans
            else:
                trans = u'%s:\n基本翻译:%s\n' % (fanyi['query'], ''.join(fanyi['translation']))
                return trans
        elif fanyi['errorCode'] == 20:
            return u'对不起，要翻译的文本过长'
        elif fanyi['errorCode'] == 30:
            return u'对不起，无法进行有效的翻译'
        elif fanyi['errorCode'] == 40:
            return u'对不起，不支持的语言类型'
        else:
            return u'对不起，您输入的单词%s无法翻译,请检查拼写' % word

    def getUsage(self):
        list = [u'\ue148翻译使用指南\n\n']
        list.append(u'使用示例：\n')
        list.append(u'    翻译我是中国人\n')
        list.append(u'    翻译dream\n')
        list.append(u'    翻译さようなら\n\n')
        list.append(u'回复“help”显示主菜单')
        return ''.join(list)

class Joke:
    def getjoke(self):
        import urllib2
        import json
        import urllib
        url = 'http://xyapi.sinaapp.com/Api/?type=joke'
        data = {'use':'test', 'key':'test', 'show':'json'}
        html = ((urllib2.urlopen(url,urllib.urlencode(data)))).read()
        joke = (json.loads(html))['joke']
        joke_info = u'%s' % (''.join(joke))
        return joke_info

class Historytoday:
    def gethistory(self):
        import urllib2
        import re
        url = 'http://www.rijiben.com'
        html = urllib2.urlopen(url).read()
        div = re.findall(r'.*?<div class=\"listren\">(.*?)</div>.*?', html, re.S)
        list = [u'≡≡历史上的今天≡≡']
        for aa in re.split('[\n]+', div[0]):
            bb = re.findall(r'.*?">(.*?)</a>&nbsp;&nbsp;</li>.*?', aa, re.S)
            if len(bb) > 0:
                list.append('\n\n')
                list.append(bb[0])
        replyText = ''.join(list)
        return replyText